from typing import Optional
from PySide6.QtCore import QObject, Slot, QPointF
from PySide6.QtCharts import QXYSeries
from PySide6.QtQml import QmlElement

QML_IMPORT_NAME = "BDM"
QML_IMPORT_MAJOR_VERSION = 1

@QmlElement
class ChartDataSource(QObject):
    
    MAX_DISPLAY_POINT_NUM = (8 * 100) # 8秒 100HZ
    
    def __init__(self, parent: QObject | None = ...) -> None:
        super().__init__(parent)
        self._series = None
        self._points = []
    
    @Slot(QXYSeries)
    def attach_series(self, series: QXYSeries):
        self._series = series
        if self._series is not None:
            self._series.replace(self._points)
            
    @Slot()
    def detach_series(self):
        self._series.replace([])
        self._series = None
        
    def add_data(self, x: float, y: float):
        self._points.append(QPointF(x, y))
        if len(self._points) > ChartDataSource.MAX_DISPLAY_POINT_NUM:
            self._points.pop(0)
        if self._series is not None:
            self._series.replace(self._points)
            if len(self._points) >= ChartDataSource.MAX_DISPLAY_POINT_NUM:
                x_axes = self._series.attachedAxes()[0]
                min_x = self._points[0]
                max_x = self._points[-1]
                x_axes.setRange(min_x.x(), max_x.x())